import React, { useState, useEffect } from 'react'
import { Table, Button, notification } from 'antd'

import {
  DeleteOutlined,
  EditOutlined,
  VerticalAlignTopOutlined,
} from '@ant-design/icons'
import axios from 'axios'
import { useNavigate } from 'react-router-dom'

export default function NewsDraft() {
  const navigator = useNavigate()
  const [DataList, setDataList] = useState([])
  const {username}  = JSON.parse(localStorage.getItem("token"))

  useEffect(() => {
    getNews()
  }, [username])

  const getNews = () => {
    axios.get(`/news?author=${username}&auditState=0&_expand=category`).then((res) => {
      setDataList(res.data)
    })
  }
  const deletItem = (item) => {
    axios.delete(`/news/${item.id}`).then((res) => {
      getNews()
    })
  }
  const EditItem = (item) => {
    // navigator(`/news-manage/update/${item.id}`)
    navigator('/news-manage/add', { state: { id: item.id } });
  }
  const submitItem = (id) => {
    axios
      .patch(`/news/${id}`, {
        auditState: 1,
      })
      .then((res) => {
        navigator('/audit-manage/list')

        notification.info({
          message: `通知`,
          description: `您可以到${'审核列表'}中查看您的新闻`,
          placement: 'bottomRight',
        })
      })
  }

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width:120
    },
    {
      title: '新闻标题',
      dataIndex: 'title',
      key: 'title',
      render: (title, item) => {
        return <a href={`/news-manage/preview/${item.id}`}>{title}</a>
      },
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
    },
    {
      title: '分类',
      key: 'category',
      render:(item)=>{
        return item.category.title
      }
    },
    {
      title: '操作',
      key: 'operate',
      render: (item) => {
        return (
          <div>
            <Button
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => deletItem(item)}
            />
            <Button
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => EditItem(item)}
            />
            <Button
              type="primary"
              shape="circle"
              icon={<VerticalAlignTopOutlined />}
              onClick={() => submitItem(item.id)}
            />
          </div>
        )
      },
    },
  ]
  return (
    <div>
      <Table
        columns={columns}
        dataSource={DataList}
        pagination={{
          pageSize: 5,
        }}
      />
    </div>
  )
}
